package com.chidopi.market.aa.dao.impl;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.chidopi.market.aa.dao.ICityPermissionDao;

public class CityPermissionDaoImpl implements ICityPermissionDao {
	private static Logger logger = LoggerFactory.getLogger(CityPermissionDaoImpl.class);

	protected SimpleJdbcTemplate simpleJdbcTemplate;
	@Autowired
	public void init(DataSource datasource) {
		this.simpleJdbcTemplate = new SimpleJdbcTemplate(datasource);
		logger.debug("init: after new JdbcTemplate");
	}
	
	@Override
	public int getCityPermission(int userId, String uri) {
		logger.info("userid={}/uri={}", userId, uri);
		String sql = "select id from bookcities where cityname in (" + 
			"select x.functionname from functions x, functions a, role2function b, account2role c, accounts d " +
			"where d.id=? and d.id=c.account_id and c.role_id=b.role_id and b.function_id=a.id and a.url=? and a.parent_id=x.id)";
		try {
			return this.simpleJdbcTemplate.queryForInt(sql, userId, uri);
//			List<Map<String, Object>> list = this.simpleJdbcTemplate.queryForList(sql, username);
//			if (list != null && list.size() > 0) {
//				int n = list.size();
//				Integer[] cities = new Integer[n];
//				for (int i=0; i<n; i++) {
//					cities[i] =  (Integer) list.get(i).get("ID");
//					logger.debug("" + cities[i]);
//				}
//				return cities;
//			}
		} catch (Exception e) {
			logger.warn("getCityPermission", e);
			return 0;
		}
	}

}
